package cn.fudan.pms.dao;


import cn.fudan.pms.domain.bo.JobBO;
import cn.fudan.pms.domain.bo.SubJobBO;
import cn.fudan.pms.domain.po.*;
import cn.fudan.pms.mbg.mapper.EquipmentMapper;
import cn.fudan.pms.mbg.mapper.JobMapper;
import cn.fudan.pms.mbg.mapper.JobRecordMapper;
import cn.fudan.pms.mbg.mapper.SubJobMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

@Repository
public class JobDao {
    @Autowired
    private SubJobMapper subJobMapper;
    @Autowired
    private JobMapper jobMapper;
    @Autowired
    private JobRecordMapper jobRecordMapper;
    @Autowired
    private EquipmentMapper equipmentMapper;


    public JobBO getJobByUuid(String uuid) {
        JobExample jobExample = new JobExample();
        jobExample.createCriteria().andUuidEqualTo(uuid);
        List<Job> jobList = jobMapper.selectByExample(jobExample);
        JobBO ret = new JobBO();
        BeanUtils.copyProperties(jobList.get(0), ret);

        SubJobExample subJobExample = new SubJobExample();
        subJobExample.createCriteria().andJobUuidEqualTo(uuid);
        List<SubJob> subJobList = subJobMapper.selectByExample(subJobExample);
        List<SubJobBO> subJobBOS = new ArrayList<>();
        for (SubJob subJob : subJobList) {
            JobRecordExample recordExample = new JobRecordExample();
            recordExample.createCriteria().andSubJobUuidEqualTo(subJob.getUuid());
            List<JobRecord> recordList = jobRecordMapper.selectByExample(recordExample);
            SubJobBO subJobBO = new SubJobBO();
            BeanUtils.copyProperties(subJob, subJobBO);
            subJobBO.setRecords(recordList);
            subJobBO.setEquipment(equipmentMapper.selectByPrimaryKey(subJob.getEquipmentId()));
            subJobBOS.add(subJobBO);
        }
        ret.setSubJobBOS(subJobBOS);
        return ret;
    }

    public SubJob getLastSubJob(String jobUuid) {
        SubJobExample subJobExample = new SubJobExample();
        subJobExample.createCriteria().andJobUuidEqualTo(jobUuid);
        List<SubJob> subJobList = subJobMapper.selectByExample(subJobExample);
        subJobList.sort(Comparator.comparing(SubJob::getStartTime));
        return subJobList.get(subJobList.size()-1);
    }
}
